在Ruby on Rails有很多神奇又好用的黑魔法,但有幾個類似的方法會搞不清楚到底在哪個狀況時要用哪個method...
我在寫rails的時候曾經踩過一個小雷:
現在這個使用者的name欄位是空的,所以回傳的是nil,如果此時在current_user.name後接的是.empty?就會噴錯,所以要用.nil?
if current_user.name.nil? #原本寫的是.empty?
redirect_to edit_user_registration_path
else
#下略
還記得有句快說到爛的話,「在Ruby幾乎所有東西都是物件,除了block」,所以nil也是物件。
nil.class
=> NilClass
nil.nil?
=> true
a = nil
a.nil? = true
"".nil?
=> false
false.nil?
=> false
[].nil?
=> false
可以很簡單地看出結果,只要.nil?之前接的物件是nil的話會回傳true,其他則都會回傳flase。
.empty方法前面是針對string array hash使用,如果這三種物件的長度為0 (legth == 0)的話,就會回傳true否則回傳flase。
另一種情況,如果.empty?前接的不是這三種物件的話,則會噴undefined method empty?。
"".empty?
=> true
[].empty?
=> true
[ ].empty?
=> true
" ".empty? #空白字串也有長度
=> false
nil.empty?
NoMethodError: undefined method `empty?' for nil:NilClass
false.empty?
NoMethodError: undefined method `empty?' for false:FalseClass
.blank?是一個ActiveRecord method,針對 nil string array hash 使用,在 false nil empty或空白字串(不是length == 0)時會回傳 true,否則回傳false。
false.blank?
=> true
nil.blank?
=> true
"".blank?
=> true
" ".blank?
=> true #(跟.empty?不同)
[].blank?
=> true
{}.blank?
=> true
.present?來自·Active Record,其實就是.blank?的相反用法,換句話說就是:
!object.blank? == object.present?
參考資料:
Rails I18n 多語系
How to use .nil? .empty? .blank? .present? in Rails 5
.nil? .empty? .blank? .present? 傻傻分不清楚?
Ruby API
“The two most powerful warriors are patience and time.”
— Leo Tolstoy, Novelist
本文同步發佈於: https://louiswuyj.tw/